/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
/**
 * 将字符串格式为yyyy-MM-dd的字符串转换成日期
 * @param fDate
 * @returns {Date}
 */
function strToDate(fDate){
    var fullDate = fDate.split("-");
    return new Date(fullDate[0], fullDate[1]-1, fullDate[2], 0, 0, 0);
}

$(function () {
    org.breezee.page = {
        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            var loginVendorId = $("#_loginVendorId").val();
            if((loginCustomerId != null && loginCustomerId != "")
                || (loginVendorId != null && loginVendorId != "")){

                var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
                var ajaxType="get"
                var optionParam='{"properties":{}}'
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);

            }else{
                var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);
            }

            Dolphin.form.parse();
            this._dataList = this.dataList('#dataList');
            this.initEvent();
            var shopCondition = {"selectCustomerId": loginCustomerId };
            if(loginCustomerId != null && loginCustomerId != ""){
                var _this = $("#shop_select");
                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : shopCondition}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
            }
            $(".js-example-basic-single").select2();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;
            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function(e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13){
                    $(".btn-query").click();
                }
            });

            $('.content-refresh').click(function () {
                me._userList.reload();
            });

            //选择客户
            $("#customer_select").change(function(){
                $("#shop_select").empty();
                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $(this).val();
                // if($("#followedFlag").is(':checked')){
                //     queryConditionObj.followed = 'Y';
                // }
                queryConditionObj.selectShopType = $("#shopType").val();
                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

            });

            //选择门店类型
            $("#shopType").change(function(){

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $("#customer_select").val()|| $("#_loginCustomerId").val();
                // if($("#followedFlag").is(':checked')){
                //     queryConditionObj.followed = 'Y';
                // }
                queryConditionObj.selectShopType = $(this).val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

            });

            $(".btn_quota").click(function () {
                $(".btn_clicked").removeClass('btn_clicked').addClass('btn_unclicked');
                $(this).removeClass('btn_unclicked').addClass('btn_clicked');
            });

            //导出
            $(".btn-export").click(function () {

                var url = (org.breezee.context.contextPath=='/'?'':org.breezee.context.contextPath)
                           +'/api/fe1222f770a54abca1a4643345d5ed11';
                var form = $("<form />");
                form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                $('body').append(form);
                var titleObj = {};
                $.each(me._dataList.__columns, function(index, obj){
                    titleObj[obj.code] = obj.title;
                });
                var value = Dolphin.json2string(titleObj);
                var input = $("<input>");
                input.attr({"name": "data[0]", "value": value, "type": "hidden"});
                form.append(input);

                $.each(me._dataList.data.rows, function(index, obj){
                    var value = Dolphin.json2string(obj.properties);
                    var input = $("<input>");
                    input.attr({"name": "data["+(++index)+"]", "value": value, "type": "hidden"});
                    form.append(input);
                });

                var input = $("<input>");
                input.attr({"name": "excelName", "value": Dolphin.i18n.get("stores.timeComparison")+Dolphin.date2string(new Date(),'yyyyMMddhhmmss'), "type": "hidden"});
                form.append(input);
                console.log(me._dataList);
                form.submit();
                form.remove();
            });

            //分析
            $(".btn-query").click(function () {

                var shopId = $("#shop_select").val();
                var shopName = $("#shop_select").find("option:selected").text();
                if(shopId == null || shopId == ''){
                    Dolphin.alert("请选择门店！");
                    return;
                }

                var startDateStr1 = $("#startDate1").val();
                var endDateStr1 = $("#endDate1").val();
                var startDateStr2 = $("#startDate2").val();
                var endDateStr2 = $("#endDate2").val();

                if(startDateStr1 == '' || endDateStr1 == ''
                || startDateStr2 == '' || endDateStr2 == ''){
                    Dolphin.alert(Dolphin.i18n.get("stores.pleaseSelectCPeriod"));
                    return;
                }

                //校验两个时间段天数是否一致
                var startDate1 = Dolphin.string2date(startDateStr1+' 00:00:00','yyyy-MM-dd hh:mm:ss');
                var endDate1 = Dolphin.string2date(endDateStr1+' 23:59:59','yyyy-MM-dd hh:mm:ss');
                var startDate2 = Dolphin.string2date(startDateStr2+' 00:00:00','yyyy-MM-dd hh:mm:ss');
                var endDate2 = Dolphin.string2date(endDateStr2+' 23:59:59','yyyy-MM-dd hh:mm:ss');
                var cntDay1 = Math.ceil(Math.abs(endDate1.getTime() - startDate1.getTime()) / 1000/ 60/ 60/ 24);
                var cntDay2 = Math.ceil(Math.abs(endDate2.getTime() - startDate2.getTime()) / 1000/ 60/ 60/ 24);
                if(cntDay1 != cntDay2){
                    Dolphin.alert(Dolphin.i18n.get("stores.pleaseSelectAgain"));
                    return;
                }

                //对比数据明细
                $("#dataList").empty();
                me._dataList = new Dolphin.LIST({
                    panel: '#dataList',
                    idField: 'id',
                    columns: [{
                        code: 'properties.day1',
                        title: Dolphin.i18n.get("time.timeQuantumOne")
                    }, {
                        code: 'properties.num1',
                        title: Dolphin.i18n.get("stores.passengerFlowNumber1")
                    },{
                        code: 'properties.index',
                        title:Dolphin.i18n.get("stores.whatDay")
                    },{
                        code: 'properties.day2',
                        title: Dolphin.i18n.get("time.timeQuantumTwo")
                    }, {
                        code: 'properties.num2',
                        title: Dolphin.i18n.get("stores.passengerFlowNumber2")
                    }],
                    multiple: false,
                    rowIndex: true,
                    checkbox: false,
                    pagination:false
                });


                $('body > #loading').show(function(){

                    $("#showDataDiv").css({width: "1200px",height:"600px"});
                    // 基于准备好的dom，初始化echarts实例
                    var myChart = echarts.init(document.getElementById('showDataDiv'));
                    // 指定图表的配置项和数据
                    var chartOption = {
                        title: {
                            text: ''
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            data:[]
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true,
                            width:'92%'
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: []
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [

                        ]
                    };

                    var queryConditionObj = Dolphin.form.getValue('.query-form');
                    queryConditionObj.customer_id_obj_ae = shopId;

                        Dolphin.ajax({
                            url: '/api/e6040baa72d740b6aac64dfef5106191',
                            type: Dolphin.requestMethod.POST,
                            async : false,
                            data: Dolphin.json2string({properties : queryConditionObj}),
                            onSuccess: function (reData) {
                                me._dataList.loadData(reData);

                                chartOption.xAxis.data = [];
                                chartOption.series = [];
                                chartOption.legend.data[0] = Dolphin.i18n.get("time.timeQuantumOne")+'('+startDateStr1+'~'+endDateStr1+')';
                                chartOption.legend.data[1] = Dolphin.i18n.get("time.timeQuantumTwo")+'('+startDateStr2+'~'+endDateStr2+')';
                                var xArray = [];
                                var yArray1 = [];
                                var yArray2 = [];
                                $.each(reData.rows,function(index,obj){
                                    xArray.push(obj.properties.index);
                                    yArray1.push(obj.properties.num1);
                                    yArray2.push(obj.properties.num2);
                                });
                                chartOption.xAxis.data = xArray;
                                chartOption.series[0] = {};
                                chartOption.series[0].name = Dolphin.i18n.get("time.timeQuantumOne")+'('+startDateStr1+'~'+endDateStr1+')';
                                chartOption.series[0].type = 'line';
                                chartOption.series[0].data = yArray1;
                                chartOption.series[1] = {};
                                chartOption.series[1].name = Dolphin.i18n.get("time.timeQuantumTwo")+'('+startDateStr2+'~'+endDateStr2+')';
                                chartOption.series[1].type = 'line';
                                chartOption.series[1].data = yArray2;

                            }
                        });

                    // 使用刚指定的配置项和数据显示图表。
                    myChart.setOption(chartOption,true);

                    $('body > #loading').hide();
                });
            });

        },
        dataList: function (panelId) {}
    };
    org.breezee.page.init();

});